// pages/detail/maillist/maillist.js
var app = getApp();
let testAddr = app.globalData.testAddr;
let imgurl = app.globalData.imgurl
var WebIM = require('../../../utils/WebIM.js').default;
let disp = require("../../../utils/broadcast");
let systemReady = false;
let det_arr = []
Page({

  /**
   * 页面的初始数据
   */
  data: {
    search_btn: true,
    search_friend: false,
    show_mask: false,
    myName: "",
    member: [],
    messageNum: "",
    unReadSpot: false,
    head_bg: imgurl + '/guest/bg.jpg',
    login: [{
        id: "0",
        logname: "联系人",
        img: '../../../image/detail/person.png',
        focus_img: '../../../image/detail/person_focus.png'
      },
      {
        id: "1",
        logname: "群聊",
        img: '../../../image/detail/friend.png',
        focus_img: '../../../image/detail/friend_focus.png'

      }, {
        id: "2",
        logname: "添加",
        img: '../../../image/detail/add_icon.png',
        focus_img: '../../../image/detail/add_icon.png'
      }
    ],
    currentTabsIndex: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(option) {
    wx.showLoading({
      title: '请稍后~',
    })
    det_arr = [];
    var me = this;
    // me.friendList(1028)
    disp.on("em.xmpp.subscribe", function() {
      me.setData({
        messageNum: getApp().globalData.saveFriendList.length
      });
    });
    disp.on("em.xmpp.contacts.remove", function(message) {
      // 个人操作，不用判断 curPage
      me.getRoster();
    });
    disp.on("em.xmpp.unreadspot", function(count) {
      me.setData({
        unReadSpot: count > 0
      });
    });
    this.setData({
      myName: wx.getStorageSync("list").guestid
    });
  },
  // 获取好友列表http://www.goods-asked.cn:8888/hwsjEmp/linkman/friendList
    // friendList: function (id) {
    //   var that = this
    //   app.util.request({
    //     url: testAddr + "/linkman/friendList?guestID=" + id,
    //     method: "POST",
    //     data: {},
    //     success: function (res) {
    //       var jsonStr = res.data.result;
    //       if (typeof jsonStr != 'object' && jsonStr != '') {
    //         jsonStr = jsonStr.replace(/\ufeff/g, "");//重点
    //         var jsonstr = JSON.parse(jsonStr);
    //       }
         
    //       console.log(jsonstr)
    //     },
    //     fail: function (res) {

    //     },
    //     complete: function (res) {
    //       wx.hideLoading()
    //     },
    //   });
    // },

  //  根据guestid查询详细信息
  detail: function (id, callback) {
    var that = this
    var arr;
    app.util.request({
      url: testAddr + "/Guest/GetInfoByID?guestID=" + id,
      method: "POST",
      data: {},
      success: function (res) {
        arr = res.data
        that.callback(arr.imgUrl)
      },
      fail: function (res) {

      },
      complete: function (res) {
        wx.hideLoading()
      },
    });
  },
  onTabsItemTap: function(event) {
    var index = event.currentTarget.dataset.index;
    this.setData({
      currentTabsIndex: 0
    });
    if (index == 1) {
      wx.navigateTo({
        url: "../groups/groups?myName=" + this.data.myName
      });
      this.setData({
        currentTabsIndex: 0
      });
    }
    if (index == 2) {
      wx.navigateTo({
        url: '../../addFri/addFri',
      })
      this.setData({
        currentTabsIndex: 0
      });
    }
  },
  onShow() {
    det_arr = []
    this.setData({
      messageNum: getApp().globalData.saveFriendList.length,
      unReadSpot: getApp().globalData.unReadSpot,
    });
    this.getRoster();
  },

  getRoster() {
    let me = this;
    let rosters = {
      success(roster) {
        var member = [];
        for (let i = 0; i < roster.length; i++) {
          if (roster[i].subscription == "both") {
            member.push(roster[i]);
          }
        }
        for (var i = 0; i < member.length; i++) {
          me.detail(member[i].name, me.callback)
        }
        me.setData({
          member: member
        });
        wx.setStorage({
          key: "member",
          data: me.data.member
        });
        if (!systemReady) {
          disp.fire("em.main.ready");
          systemReady = true;
        }
      },
      error(err) {
        console.log("[main:getRoster]", err);
      }
    };
    // WebIM.conn.setPresence()
    WebIM.conn.getRoster(rosters);
  },
  callback(list) {
    wx.hideLoading()
    var that = this
    var oldArr = that.data.member
    for (var i = 0; i < oldArr.length; i++) {
      if (list.guestid == oldArr[i].name) {
        oldArr[i].imgUrl = imgurl + 'guest/' + list.imgUrl
        oldArr[i].username = list.guestName
      }
    }
    this.setData({
      member: oldArr
    })
  },
  //  根据guestid查询详细信息
  detail: function (id, callback) {
    var that = this
    var arr;
    app.util.request({
      url: testAddr + "/Guest/GetInfoByID?guestID=" + id,
      method: "POST",
      data: {},
      success: function (res) {
        arr = res.data
        that.callback(arr)
      },
      fail: function (res) {

      },
      complete: function (res) {
        wx.hideLoading()
      },
    });
  },
  moveFriend: function(message) {
    let me = this;
    let rosters = {
      success: function(roster) {
        var member = [];
        for (let i = 0; i < roster.length; i++) {
          if (roster[i].subscription == "both") {
            member.push(roster[i]);
          }
        }
        me.setData({
          member: member
        });
      }
    };
    if (message.type == "unsubscribe" || message.type == "unsubscribed") {
      WebIM.conn.removeRoster({
        to: message.from,
        success: function() {
          WebIM.conn.unsubscribed({
            to: message.from
          });
          WebIM.conn.getRoster(rosters);
        }
      });
    }
  },

  handleFriendMsg: function(message) {
    wx.showModal({
      title: "添加好友请求",
      content: message.from + "请求加为好友",
      success: function(res) {
        if (res.confirm == true) {
          WebIM.conn.subscribed({
            to: message.from,
            message: "[resp:true]"
          });
          WebIM.conn.subscribe({
            to: message.from,
            message: "[resp:true]"
          });
        } else {
          WebIM.conn.unsubscribed({
            to: message.from,
            message: "rejectAddFriend"
          });
        }
      },
      fail: function(err) {}
    });
  },
  //按下事件开始
  mytouchstart: function(e) {
    let that = this;
    that.setData({
      touch_start: e.timeStamp
    })
    console.log(e.timeStamp + '- touch-start')
  },
  //按下事件结束
  mytouchend: function(e) {
    let that = this;
    that.setData({
      touch_end: e.timeStamp
    })
    console.log(e.timeStamp + '- touch-end')
  },

  openSearch: function() {
    this.setData({
      search_btn: false,
      search_friend: true,
      show_mask: true
    });
  },

  cancel: function() {
    this.setData({
      search_btn: true,
      search_friend: false,
      show_mask: false
    });
  },

  add_new: function() {
    wx.navigateTo({
      url: "../add_new/add_new"
    });
  },

  tab_chat: function() {
    wx.redirectTo({
      url: "../chat/chat"
    });
  },

  close_mask: function() {
    this.setData({
      search_btn: true,
      search_friend: false,
      show_mask: false
    });
  },

  tab_setting: function() {
    wx.redirectTo({
      url: "../settings/settings"
    });
  },

  into_inform: function() {
    wx.navigateTo({
      url: "../inform/inform?myName=" + this.data.myName
    });
  },

  into_groups: function() {
    wx.navigateTo({
      url: "../groups/groups?myName=" + this.data.myName
    });
  },

  into_room: function(event) {
    let that = this;
    //触摸时间距离页面打开的毫秒数
    var touchTime = that.data.touch_end - that.data.touch_start;
    //如果按下时间大于350为长按
    if (touchTime > 350) {
      var delName = event.target.dataset.username;
      var myName = wx.getStorageSync("myUsername"); // 获取当前用户名
      wx.showModal({
        title: "确认删除好友" + delName+'吗?',
        cancelText: "取消",
        confirmText: "删除",
        success(res) {
          if (res.confirm == true) {
            WebIM.conn.removeRoster({
              to: delName,
              success: function() {
                WebIM.conn.unsubscribed({
                  to: delName
                });
                wx.showToast({
                  title: "删除成功",
                });
                // 删除好友后 同时清空会话
                wx.setStorageSync(delName + myName, "");
                wx.setStorageSync("rendered_" + delName + myName, "");
              },
              error: function(error) {

              }
            });
          }
        }
      });
    } else {
      var nameList = {
        myName: this.data.myName,
        your: event.target.dataset.username
      };
      wx.navigateTo({
        url: "../chatroom/chatroom?username=" + JSON.stringify(nameList)
      });
    }
  },

  into_info: function(event) {
    var id = event.target.dataset.username
    wx.navigateTo({
      url: '../../cardbark/personaldata/personaldata?id=' + id
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})